package com.datacow.util.baidutranslationapi;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.datacow.util.Md5Utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: 百度翻译

* @Author: 李德森
* @Date: 2021/1/20
*/
public class TransApi {

    /**
     * 请求api接口
     */
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    /**
     * 开发者ID
     */
    private static final String APP_ID = "20210119000675809";
    /**
     * 开发者密钥
     */
    private static final String SECURITY_KEY = "40BuL01ECx543KwU5mfM";

    /**
     * 获取翻译结果
     * 模版:{"from":"zh","to":"en","trans_result":[{"src":"\u963f\u62c9\u65af\u52a0","dst":"Alaska"}]}
     *
     * @param query
     * @param from
     * @param to
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getTransResult(String query, String from, String to) throws Exception {
        Map<String, String> params = buildParams(query, from, to);
        //返回的结果是一个JSON字符串,
        // {"error_code":"52003","error_msg":"UNAUTHORIZED USER"}
        // 如{"from":"zh","to":"en","trans_result":[{"src":"\u963f\u62c9\u65af\u52a0","dst":"Alaska"}]}
        String body = HttpGet.get(TRANS_API_HOST, params);
        JSONObject jsonObject = JSONArray.parseObject(body);
        JSONArray trans_result = jsonObject.getJSONArray("trans_result");
        return JSONArray.parseObject(trans_result.get(0).toString()).get("dst").toString();
    }

    private static Map<String, String> buildParams(String query, String from, String to) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY;
        params.put("sign", Md5Utils.md5(src));
        return params;
    }
}
